// Copyright: Personal possession of Nguyen Minh Kha
// Description: This class mux many object, manage what you see on screen
// License: free source
// Date time: 07/07/2011(mm/dd/yyyy)
// Writer: Nguyen Minh Kha

#include "screen.h"

int Screen::screenWidth;
int Screen::screenHeight;
Screen* Screen::screen;

Screen::Screen(void)
{

}


Screen::~Screen(void)
{

}


void Screen::Release()
{
  if(this->surface != NULL) 
    this->surface->Release();
  if (d3ddev != NULL)
    d3ddev->Release();
  if (d3d != NULL)
    d3d->Release();
}


void Screen::ChangeWindowSize(int width, int height) {
  Screen::screenWidth = width;
  Screen::screenHeight = height;
}


bool Screen::Init(HWND hWnd) {
  // Init static screen
  Screen::screen = this;

  countPerFrame = 1000 / FRAMERATE;
  this->prevTick = 0;
  this->hWnd = hWnd;
  Screen::screenWidth = SCREEN_WIDTH;
  Screen::screenHeight = SCREEN_HEIGHT;
  // Init d3dpp
  ZeroMemory(&d3dpp, sizeof(d3dpp));
  d3dpp.Windowed = TRUE;
  d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
  d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
  d3dpp.BackBufferCount = 1;
  d3dpp.BackBufferHeight = SCREEN_HEIGHT;
  d3dpp.BackBufferWidth = SCREEN_WIDTH;
  d3dpp.hDeviceWindow = hWnd;
  // create master d3d interface
  d3d = Direct3DCreate9(D3D_SDK_VERSION);
  if (d3d == NULL) {
    Log::Write(L"Create D3D interface fail");
    return false;
  }
  d3d->CreateDevice(D3DADAPTER_DEFAULT, // default Screen adapter
                    D3DDEVTYPE_HAL, // hardware render
                    hWnd, // host window
                    D3DCREATE_SOFTWARE_VERTEXPROCESSING, //
                    &d3dpp,
                    &d3ddev);
  if (d3ddev == NULL) {
    Log::Write(L"Create D3D device fail");
    return false;
  }
  int result = d3ddev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, 
                                     &backBuffer);
  if (result != D3D_OK) {
        Log::Write(L"Create get backbuffer fail");
        return false;
  }
  result = d3ddev->CreateOffscreenPlainSurface(
      SCREEN_WIDTH, SCREEN_HEIGHT, D3DFMT_X8R8G8B8,
      D3DPOOL_DEFAULT, // VRam
      &surface,
      NULL);
  if (result != D3D_OK) {
        Log::Write(L"Create 'main' offscreen surface fail.");
        return false;
  }
  return true;                  
}


bool Screen::WillPrintNextFrame() {
  DWORD currentTick = GetTickCount();
  DWORD extraTick = currentTick - this->prevTick;
  if ( extraTick >= this->countPerFrame) { // print next frame
    this->prevTick = currentTick;
    return true;
  } else {
   Sleep(countPerFrame - extraTick);
    return false;
  }
}

